<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>干支纪年查询</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    th,
    td {
      padding: 10px;
      text-align: center;
      border: 1px solid #ddd;
    }

    th {
      background-color: #f2f2f2;
    }
  </style>
</head>

<body>
  <h1>干支纪年查询</h1>
  <label for="year">请输入年份：</label>
  <input type="number" id="year" placeholder="例如：1566" required>
  <button onclick="fetchGanzhiData()">查询</button>
  
  <h2>干支纪年表</h2>
  <table id="ganzhiTable">
    <thead>
      <tr>
        <th>月份</th>
        <th>日期</th>
        <th>干支</th>
      </tr>
    </thead>
    <tbody>
      <!-- 动态数据将会填充在这里 -->
    </tbody>
  </table>

  <script>
      // 获取年份并请求接口
      async function fetchGanzhiData() {
        const year = document.getElementById("year").value;
      if (!year) {
        alert("请输入有效的年份");
        return;
      }

      try {
        const response = await fetch("http://localhost:3000/generate-ganzhi", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({year: year})
        });

        if (response.ok) {
          const data = await response.json();
          displayGanzhiData(data);
        } else {
          alert("请求失败：" + response.statusText);
        }
      } catch (error) {
        console.error("请求错误:", error);
        alert("请求出错，请稍后重试");
      }
    }

      // 将返回的数据展示到表格中
      function displayGanzhiData(data) {
        const tableBody = document.getElementById("ganzhiTable").getElementsByTagName("tbody")[0];
        tableBody.innerHTML = "";  // 清空之前的内容

      data.forEach((monthData, monthIndex) => {
        monthData.forEach(dayData => {
          const row = tableBody.insertRow();
          const monthCell = row.insertCell(0);
          const dateCell = row.insertCell(1);
          const ganzhiCell = row.insertCell(2);

          monthCell.textContent = monthIndex + 1;
          dateCell.textContent = dayData.date;
          ganzhiCell.textContent = dayData.ganzhi;
        });
      });
    }
  </script>
</body>

</html>